<template>
  <div class="w-full mt-[30px]">
    <div class="text-[16px] text-[#333] font-bold mb-[25px] title">基础数据</div>
    <el-form ref="formRef" :model="form" :rules="rules" :inline="false" validateOnRuleChange>
      <el-form-item>
        <div class="">
          <div class="label">请添加资产<span class="pl-[5px] red">*</span></div>
          <div class="flex box">
            <div
              class="flex justify-center items-center cursor-pointer px-[15px] itembox"
              v-for="(item, index) in typeList"
              :key="index"
              :class="{ 'active': typeIndex === index, 'cursor-not-allowed': !isNewApp }"
              @click="changType(index)"
            >
              {{ item.label }}
            </div>
          </div>
        </div>
      </el-form-item>
      <!-- <el-form-item>
        <div class="">
          <div class="label">请选择资产创建方式<span class="pl-[5px] red">*</span></div>
          <div class="flex box">
            <div
              class="flex justify-center items-center cursor-pointer px-[15px] itembox"
              v-for="(item, index) in methodList"
              :key="index"
              :class="{ 'active': methodIndex === index, 'cursor-not-allowed': isEdit }"
              @click="changMethodType(index)"
            >
              {{ item.label }}
            </div>
          </div>
        </div>
      </el-form-item> -->
      <el-form-item prop="advertiserId">
        <div class="w-full">
          <div class="label">请选择广告账户<span class="pl-[5px] red">*</span></div>
          <div class="flex flex-col w-[380px] relative box">
            <div class="w-full" v-if="!isEdit">
              <el-select
                ref="accountSelectRef"
                v-model="form.advertiserId"
                filterable
                popper-class="single-select-loadmore"
                remote
                :remote-method="remoteMethod"
                placeholder="请选择帐户"
                v-load-more="loadMoreData"
              >
                <el-option v-for="(item, index) in accountList" :key="index" :value="item.advertiserId" :label="item.advertiserName"></el-option>
                <div class="w-full flex justify-center">
                  <div class="loading" v-if="accountLoading">
                    <svg class="circular" viewBox="0 0 50 50">
                      <circle class="path" cx="25" cy="25" r="20" fill="none" />
                    </svg>
                  </div>
                </div>
              </el-select>
            </div>
            <div class="w-full" v-else>
              <el-select ref="accountSelectRef" v-model="form.advertiserId" filterable popper-class="single-select-loadmore" disabled> </el-select>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <div class="">
          <div class="label">请选择小程序类型<span class="pl-[5px] red">*</span></div>
          <div class="flex box">
            <div
              class="flex justify-center items-center cursor-pointer px-[15px] itembox"
              v-for="(item, index) in categoriesList"
              :key="index"
              :class="{ active: categoryIndex === index, 'cursor-not-allowed': isEdit, 'color-gray': isEdit }"
              @click="changProgressType(index)"
            >
              {{ item.category_name }}
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item prop="tagInfo" v-if="categoryHasSub">
        <div class="w-full">
          <div class="label">请选择细分分类<span class="pl-[5px] red">*</span></div>
          <div class="flex flex-col w-full box">
            <div class="inputVal flex valuebox" @click="handelSubCategory">
              <div class="text-[#9d9d9d]">{{ curSelectCateInfo.categoryName || '请选择细分分类' }}</div>
              <div class="relative top-[0px] arrow" :class="showSubCategory ? 'active' : ''">
                <el-icon size="10"><ArrowDown /></el-icon>
              </div>
            </div>
            <div class="h-[200px] flex overflow-hidden cate" v-if="showSubCategory">
              <div class="w-[50%] shrink-0 h-[200px] overflow-y-scroll left">
                <div
                  class="flex justify-between items-center px-[10px] subitems cursor-pointer hover:bg-[#ccc]"
                  v-for="(item, index) in subCategoryList"
                  :key="index"
                  :class="subCategoryIndex === index ? 'active' : ''"
                  @click="selectSubCategory(index)"
                >
                  <div class="txt">{{ item.category_name }}</div>
                  <div class="arrows">
                    <el-icon size="10" v-if="!item.category_id"><ArrowRight /></el-icon>
                  </div>
                </div>
              </div>
              <div class="w-[50%] shrink-0 h-[200px] overflow-y-scroll right">
                <div
                  class="flex justify-between items-center px-[10px] subitems cursor-pointer hover:bg-[#ccc]"
                  v-for="(item, index) in thirdCategoryList"
                  :key="index"
                  :class="thirdCategoryIndex === index ? 'active' : ''"
                  @click="selectThirdCategory(index)"
                >
                  <div class="txt">{{ item.category_name }}</div>
                  <div class="arrows"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { getAccountAdvertiserList } from '@/api/advertisement/account';
import { AaccountAdvertiserVO, AaccountAdvertiserQuery, MicroAppVO } from '@/api/advertisement/account/types';
import { useAppStore } from '@/store/modules/app';

import { listTagInfo, type TagInfoVO } from '@/api/com';

const appStore = useAppStore();

const emit = defineEmits(['getValue', 'changeStep']);

const props = defineProps<{
  info?: StepVO;
  isEdit: boolean;
  isNewApp: boolean;
}>();

const isEdit = computed(() => props.isEdit);

type StepVO = {
  advertiserId: number;
  tagInfo: string;
  curSelectCateInfo?: {
    categoryId: number;
    categoryName: string;
  };
  categoryIndex?: number;
  subCategoryIndex?: number;
  thirdCategoryIndex?: number;
};

const typeIndex = ref(0);
const typeList = [
  {
    id: 1,
    label: '小程序'
  }
  //   {
  //     id: 2,
  //     label: '小游戏'
  //   }
];

const changType = (i: number) => {
  if (!props.isNewApp) {
    return;
  }
  typeIndex.value = i;
};

const methodIndex = ref(0);
const methodList = [
  {
    id: 1,
    label: '添加到帐户'
  }
  //   {
  //     id: 2,
  //     label: '小游戏'
  //   }
];

const formRef = ref();

const categoryIndex = ref(0);

const categoryHasSub = ref(true);

const subCategoryIndex = ref(-1);

const categoryList = ref<TagInfoVO>();

const showSubCategory = ref(false);

const thirdCategoryIndex = ref(-1);

const curSelectCateInfo = ref({
  categoryId: null,
  categoryName: null
});

/**
 * 计算主分类
 */
const categoriesList = computed(() => {
  return (
    categoryList.value &&
    categoryList.value.categories.map((item) => {
      return { category_name: item.category_name, category_id: item.category_id };
    })
  );
});
/**
 * 细分分类
 */
const subCategoryList = computed(() => {
  const currentCategory = categoryList.value?.categories.find((item) => {
    return item.category_name === categoriesList.value[categoryIndex.value].category_name;
  });
  // 返回找到的子类别列表
  return currentCategory && currentCategory.categories
    ? currentCategory.categories.map((subitem) => {
        return { category_name: subitem.category_name, category_id: subitem.category_id };
      })
    : [];
});

/**
 * 细分分类子分类
 */
const thirdCategoryList = computed(() => {
  const currentCategory = categoryList.value?.categories.find((item) => {
    return item.category_name === categoriesList.value[categoryIndex.value].category_name;
  });

  // 找到当前细分分类
  const subCategory = currentCategory?.categories.find((subitem) => {
    return subitem.category_name === subCategoryList.value[subCategoryIndex.value]?.category_name;
  });

  // 返回找到的子分类（第三层）
  return subCategory && subCategory.categories
    ? subCategory.categories.map((thirdItem) => {
        return { category_name: thirdItem.category_name, category_id: thirdItem.category_id };
      })
    : [];
});
const changMethodType = (i: number) => {
  if (isEdit.value) {
    return;
  }
  typeIndex.value = i;
};

const changProgressType = (i: number) => {
  if (isEdit.value) {
    return;
  }
  categoryIndex.value = i;
  showSubCategory.value = false;
  //是否显示细分分类
  if (categoriesList.value[i].category_id) {
    categoryHasSub.value = false;
  } else {
    categoryHasSub.value = true;
  }
};
/**
 *控制是否显示细分分类选项
 */
const handelSubCategory = () => {
  showSubCategory.value = !showSubCategory.value;
};
/**
 * 选择细分类
 */
const selectSubCategory = (i: number) => {
  subCategoryIndex.value = i;
  //如果选中的分类有分类id,说明没有子分类，设置选中数据
  if (subCategoryList.value[i].category_id) {
    curSelectCateInfo.value.categoryId = subCategoryList.value[i].category_id;
    curSelectCateInfo.value.categoryName = subCategoryList.value[i].category_name;
    form.value.tagInfo = curSelectCateInfo.value.categoryId;
    showSubCategory.value = false;
  }
};

const selectThirdCategory = (i: number) => {
  thirdCategoryIndex.value = i;
  //如果选中的分类有分类id,说明没有子分类，设置选中数据
  if (thirdCategoryList.value[i].category_id) {
    curSelectCateInfo.value.categoryId = thirdCategoryList.value[i].category_id;
    curSelectCateInfo.value.categoryName = thirdCategoryList.value[i].category_name;
    form.value.tagInfo = curSelectCateInfo.value.categoryId;
    showSubCategory.value = false;
  }
};

const accountIsEnd = ref(false);
const accountLoading = ref(false);
const accountList = ref<AaccountAdvertiserVO[]>([]);
const accountSelectRef = ref();

const initForm: StepVO = {
  advertiserId: null,
  tagInfo: null
};
const data = reactive<PageData<StepVO, AaccountAdvertiserQuery>>({
  form: { ...initForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: appStore.accountId,
    advertiserName: ''
  },
  rules: {
    advertiserId: [{ required: true, message: '请选择账户', trigger: 'change' }],
    tagInfo: [{ required: true, message: '请选择小程序类型', trigger: 'change' }]
  }
});

const { form, queryParams, rules } = toRefs(data);

watch(
  () => props.info,
  () => {
    if (props.info?.advertiserId) {
      if (!isEdit.value)
        nextTick(() => {
          form.value = props.info;
          curSelectCateInfo.value = props.info.curSelectCateInfo;
          categoryIndex.value = props.info.categoryIndex || -1;
          subCategoryIndex.value = props.info.subCategoryIndex || -1;
          thirdCategoryIndex.value = props.info.thirdCategoryIndex || -1;
        });
    }
  },
  {
    immediate: true
  }
);
const remoteMethod = (query: string) => {
  accountList.value = [];
  queryParams.value.pageNum = 1;
  if (query) {
    queryParams.value.advertiserName = query;
    setTimeout(async () => {
      getMoreData();
    }, 200);
  } else {
    queryParams.value.advertiserName = '';
    setTimeout(async () => {
      getMoreData();
    }, 200);
  }
};
const loadMoreData = () => {
  if (accountIsEnd.value || accountLoading.value) return;
  queryParams.value.pageNum += 1;
  getMoreData();
};

/**
 * 下拉狂获取更多账户
 */
const getMoreData = async () => {
  accountLoading.value = true;
  try {
    const res = await getAccountAdvertiserList(queryParams.value);
    accountList.value.push(...res.rows);
    accountIsEnd.value = res.rows.length < queryParams.value.pageSize ? true : false;
  } finally {
    accountLoading.value = false;
  }
};
/*
 * 获取第一页用户
 */
const init = async () => {
  accountLoading.value = true;
  try {
    const res = await getAccountAdvertiserList(queryParams.value);
    accountList.value = res.rows;
    accountIsEnd.value = res.rows.length < queryParams.value.pageSize ? true : false;
  } finally {
    accountLoading.value = false;
  }
};

const getTagInfoList = async () => {
  const res = await listTagInfo({ pageNum: 1, pageSize: 9999, type: 2 });
  categoryList.value = res.data;
};

const reset = () => {
  form.value.advertiserId = null;
  curSelectCateInfo.value = { categoryId: '', categoryName: '' };
  categoryIndex.value = 0;
  subCategoryIndex.value = -1;
  showSubCategory.value = false;
  thirdCategoryIndex.value = -1;
};

const checkRes = () => {
  formRef.value?.validate((valid) => {
    if (valid) {
      emit('changeStep', 2);
      emit('getValue', {
        advertiserId: form.value.advertiserId,
        tagInfo: form.value.tagInfo,
        curSelectCateInfo: curSelectCateInfo.value,
        categoryIndex: categoryIndex.value,
        subCategoryIndex: subCategoryIndex.value,
        thirdCategoryIndex: thirdCategoryIndex.value
      });
    }
  });
};

//找最里面的category_name
const findInnermost = (obj) => {
  if (obj.categories && obj.categories.length > 0) {
    // 递归调用，继续查找下一层
    return findInnermost(obj.categories[obj.categories.length - 1]);
  }
  // 没有子分类，返回当前的 category_name
  return obj;
};

const updateForm1Value = (value: any) => {
  const tagInfo = JSON.parse(value.tagInfo);
  form.value.advertiserId = value.advertiserId;

  curSelectCateInfo.value.categoryId = tagInfo.category_id;

  const curTag = findInnermost(tagInfo);
  curSelectCateInfo.value.categoryName = curTag.category_name;

  //类型Index
  categoryIndex.value = categoriesList.value.findIndex((e) => e.category_name === tagInfo.categories[0].category_name);
  //如果有子分类

  const currentSub = tagInfo.categories[0]?.categories[0];
  if (currentSub) {
    subCategoryIndex.value = subCategoryList.value.findIndex((e) => e.category_name === currentSub.category_name);
    const thirdSub = currentSub?.categories[0];
    if (thirdSub) {
      thirdCategoryIndex.value = thirdCategoryList.value.findIndex((e) => e.category_name === thirdSub.category_name);
    }
  }
  form.value.tagInfo = curTag.category_id;
};

defineExpose({ reset, checkRes, updateForm1Value });

onMounted(() => {
  // init();
  getTagInfoList();
});
</script>

<style lang="scss" scoped>
.itembox {
  background-color: #f1f1f1;
  border: 1px solid #f1f1f1;
  &.active {
    color: #409eff;
    background-color: #fff;
    border: 1px solid #409eff;
    &.cursor-not-allowed {
      color: #a1caff;
      background-color: #fff;
      border: 1px solid #a1caff;
    }
  }
}
.valuebox {
  justify-content: space-between !important;
  align-items: center;
  .arrow {
    transform-origin: center center;
    transition: all linear 0.1s;
    transform: rotate(0deg);
    &.active {
      transform: rotate(180deg);
    }
  }
}
.cate {
  box-shadow: 0 3px 9px rgba(0, 0, 0, 0.08);
  .left,
  .right {
    .active {
      background-color: #ccc;
    }
  }
}
</style>
